import React, { useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import { motion, AnimatePresence } from 'framer-motion';
import './customComponents.css';

interface CustomMenuItemProps {
  icon: React.ReactNode;
  label: string;
  path?: string;
  onClick?: () => void;
  children?: CustomMenuItemProps[];
  isOpen?: boolean;
  onToggle?: () => void;
}

interface CustomMenuProps {
  items: CustomMenuItemProps[];
}

const CustomMenuItem: React.FC<CustomMenuItemProps & { depth?: number }> = ({ 
  icon, 
  label, 
  path, 
  onClick, 
  children,
  depth = 0,
  isOpen,
  onToggle
}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  
  // 检查当前路径是否匹配或包含在子路径中
  const isExactMatch = location.pathname === path;
  const isChildActive = children?.some(child => 
    location.pathname.startsWith(child.path || '')
  );
  const isSelected = isExactMatch || (isChildActive && depth > 0);
  
  const [isHovered, setIsHovered] = useState(false);

  const handleClick = () => {
    // 如果有子菜单，优先处理展开/收起逻辑
    if (children && onToggle) {
      onToggle();
    } else if (onClick) {
      onClick();
    } else if (path) {
      navigate(path);
    }
  };

  // 获取菜单项样式
  const getItemStyle = () => {
    let baseClasses = "custom-menu-item";
    
    if (isSelected) {
      baseClasses += " selected";
    }
    
    return baseClasses;
  };

  // 获取箭头样式
  const getArrowClasses = () => {
    const classes = ["custom-menu-item-arrow"];
    
    if (isOpen) {
      classes.push("open");
    }
    
    return classes.join(" ");
  };

  // 获取内容样式
  const getContentClasses = () => {
    return "custom-menu-item-content";
  };

  // 获取图标样式
  const getIconClasses = () => {
    return "custom-menu-item-icon";
  };

  // 获取标签样式
  const getLabelClasses = () => {
    return "custom-menu-item-label";
  };

  return (
    <>
      <motion.div
        className={getItemStyle()}
        style={{
          margin: '4px 8px',
          paddingLeft: `${8 + depth * 16}px`,
          cursor: 'pointer',
          position: 'relative',
          overflow: 'hidden',
          transition: 'all 0.3s ease',
          backgroundColor: isSelected ? (mode === 'dark' 
              ? 'rgba(97,220,163,0.1)' 
              : 'rgba(24,144,255,0.1)') : 'transparent'
        }}
        onClick={handleClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        whileHover={{ 
          x: 4,
          backgroundColor: isHovered ? (mode === 'dark' 
            ? 'rgba(97,220,163,0.2)' 
            : 'rgba(24,144,255,0.2)') : (isSelected ? (mode === 'dark' 
              ? 'rgba(97,220,163,0.1)' 
              : 'rgba(24,144,255,0.1)') : 'transparent'),
          boxShadow: isHovered ? (mode === 'dark' 
            ? '0 4px 12px rgba(97,220,163,0.15)' 
            : '0 4px 12px rgba(24,144,255,0.15)') : 'none'
        }}
        whileTap={{ scale: 0.98 }}
        initial={{ opacity: 0, x: -20 }}
        animate={{ opacity: 1, x: 0 }}
        transition={{ duration: 0.3 }}
      >
        <div className={getContentClasses()}>
          <motion.span 
            className={getIconClasses()}
            animate={{ 
              scale: isSelected ? 1.1 : 1,
              rotate: isSelected ? 5 : 0
            }}
            transition={{ duration: 0.3 }}
          >
            {icon}
          </motion.span>
          <motion.span 
            className={getLabelClasses()}
            animate={{ 
              fontWeight: isSelected ? 'bold' : 'normal'
            }}
            transition={{ duration: 0.3 }}
          >
            {label}
          </motion.span>
          {children && (
            <motion.span 
              className={getArrowClasses()}
              style={{ 
                fontSize: '12px'
              }}
              animate={{ 
                rotate: isOpen ? 90 : 0
              }}
              transition={{ duration: 0.2 }}
            >
              ▶
            </motion.span>
          )}
        </div>
      </motion.div>
      
      {children && (
        <AnimatePresence>
          {isOpen && (
            <motion.div
              initial={{ height: 0, opacity: 0 }}
              animate={{ height: 'auto', opacity: 1 }}
              exit={{ height: 0, opacity: 0 }}
              transition={{ duration: 0.2 }}
              style={{ overflow: 'hidden' }}
            >
              {children.map((child, index) => {
                // 提取key属性，避免在JSX中传播key
                const { path, label, ...childProps } = child;
                const key = path || index;
                
                return (
                  <CustomMenuItem
                    key={key}
                    {...childProps}
                    path={path}
                    label={label}
                    depth={depth + 1}
                  />
                );
              })}
            </motion.div>
          )}
        </AnimatePresence>
      )}
    </>
  );
};

const CustomMenu: React.FC<CustomMenuProps> = ({ items }) => {
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({});
  const location = useLocation();
  
  // 根据当前路径自动展开包含活动子项的菜单
  React.useEffect(() => {
    const newOpenMenus: Record<string, boolean> = {};
    
    const findActiveParent = (items: CustomMenuItemProps[]): string | null => {
      for (const item of items) {
        if (item.path && location.pathname.startsWith(item.path) && item.children) {
          return item.path;
        }
        if (item.children) {
          const found = findActiveParent(item.children);
          if (found) return found;
        }
      }
      return null;
    };
    
    const activeParent = findActiveParent(items);
    if (activeParent) {
      newOpenMenus[activeParent] = true;
    }
    
    setOpenMenus(newOpenMenus);
  }, [location.pathname, items]);
  
  const handleToggle = (path: string) => {
    setOpenMenus(prev => ({
      ...prev,
      [path]: !prev[path]
    }));
  };

  return (
    <div className="w-full">
      {items.map((item, index) => {
        // 提取key属性，避免在JSX中传播key
        const { path, label, ...itemProps } = item;
        const key = path || label;
        
        return (
          <motion.div
            key={key}
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: index * 0.1 }}
          >
            <CustomMenuItem
              {...itemProps}
              path={path}
              label={label}
              isOpen={item.children ? openMenus[key] : undefined}
              onToggle={item.children ? () => handleToggle(key) : undefined}
            />
          </motion.div>
        );
      })}
    </div>
  );
};

export default CustomMenu;